<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VGroup>
          <el-select v-model="form.input.type" style="width: 130px">
            <el-option label="备库需求单号" value="demand_no"></el-option>
            <el-option label="采购单号" value="purchase_no"></el-option>
            <el-option label="供应商" value="supplier_name"></el-option>
            <el-option label="产品名称" value="sku_name"></el-option>
            <el-option label="ASIN" value="asin"></el-option>
          </el-select>
          <VBatchInput v-model="form.input.value" placeholder="请输入" class="w-40" @search="query" />
        </VGroup>
        <VGroup>
          <el-select v-model="form.sku.type" class="w-28">
            <el-option label="sku" value="sku"></el-option>
            <el-option label="赛盒SKU" value="sai_he_sku"></el-option>
            <el-option label="自定义sku" value="custom_sku"></el-option>
          </el-select>
          <VBatchInput v-model="form.sku.value" placeholder="请输入" class="w-40" @search="query" />
        </VGroup>
        <VSelect v-model="form.demand_type" placeholder="备库需求类型" :options="options.demand_type" multiple collapse-tags style="min-width: 160px" />
        <VGroup>
          <el-select v-model="form.user.type" style="width: 130px">
            <el-option label="采购人员" value="purchase_user_id"></el-option>
            <el-option label="开发人员" value="develop_user_id"></el-option>
            <el-option label="供应商负责人员" value="director_id"></el-option>
            <el-option label="申请人员" value="create_user_id"></el-option>
          </el-select>
          <VCascader v-model="form.user.value" placeholder="人员" multiple collapse-tags style="min-width: 160px" />
        </VGroup>
        <VCascader v-model="form.department_name" placeholder="需求部门" type="department" multiple collapse-tags checkStrictly style="min-width: 160px" />
        <VSelect v-model="form.demand_status" placeholder="审核状态" :options="options.demand_status" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.country" placeholder="国家" :options="options.country" multiple collapse-tags style="min-width: 160px" />
        <VGroup>
          <el-select v-model="form.warehouse.type" class="w-28" @change="form.warehouse.value = []">
            <el-option label="目的仓平台" value="destination_warehouse"></el-option>
            <el-option label="目的仓" value="plan_destination_warehouse"></el-option>
          </el-select>
          <VSelect v-if="form.warehouse.type === 'destination_warehouse'" v-model="form.warehouse.value" placeholder="请选择" :options="options.destination_warehouse" multiple
            collapse-tags style="min-width: 160px" />
          <VSelect v-else v-model="form.warehouse.value" placeholder="请选择" :options="options.plan_destination_warehouse" multiple collapse-tags style="min-width: 160px" />
        </VGroup>
        <VSelect v-model="form.sku_purchase_status" placeholder="采购状态" :options="options.sku_purchase_status" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.purchase_inbound_status" placeholder="入库状态" :options="options.purchase_status" multiple collapse-tags style="min-width: 160px" />
        <VCascader v-model="form.sale_id" placeholder="负责销售" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.transport_type" placeholder="运输方式" :options="options.transport_type" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.is_new" placeholder="是否新品" :options="options.is_complete" multiple collapse-tags style="min-width: 160px" />
        <VGroup>
          <div class="v-group-item">采购周期</div>
          <el-input-number v-model="form.purchase_day.start" placeholder="最小" :controls="false" :min="0" :step="1" :precision="0" class="w-20" />
          <div class="v-group-item">-</div>
          <el-input-number v-model="form.purchase_day.end" placeholder="最大" :controls="false" :min="0" :step="1" :precision="0" class="w-20" />
        </VGroup>
        <VSelect v-model="form.period_id" placeholder="结算方式" type="period" multiple collapse-tags style="min-width: 220px" />
        <VSelect v-model="form.is_change" placeholder="是否变更" :options="options.is_change" multiple collapse-tags style="min-width: 120px" />
        <VSelect v-model="form.is_deliver_abnormal" placeholder="是否到货异常" :options="options.is_deliver_abnormal" multiple collapse-tags style="min-width: 140px" />
        <VSelect v-model="form.plan_order_status" placeholder="是否生成发货计划" :options="options.plan_order_status" multiple collapse-tags style="min-width: 166px" />
        <VSelect v-model="form.is_purchase_plan" placeholder="是否有备料" :options="options.is_purchase_plan" multiple collapse-tags style="min-width: 166px" />
        <VSelect v-model="form.reject_type" placeholder="驳回原因" :options="options.reject_type" multiple collapse-tags style="min-width: 160px" />
        <VGroup>
          <el-select v-model="form.num.type" style="width: 130px">
            <el-option label="剩余发货数" value="tc_leave_num"></el-option>
            <el-option label="采购待下单数" value="sku_leave_num"></el-option>
            <el-option label="采购已下单数" value="sku_purchase_num"></el-option>
            <el-option label="采购单收货数" value="purchase_deliver_num"></el-option>
            <el-option label="采购单入库数" value="purchase_inbound_num"></el-option>
          </el-select>
          <el-input-number v-model="form.num.start" placeholder="最小" :controls="false" :min="0" :step="1" :precision="0" class="w-20" />
          <div class="v-group-item">-</div>
          <el-input-number v-model="form.num.end" placeholder="最大" :controls="false" :min="0" :step="1" :precision="0" class="w-20" />
        </VGroup>
        <VSelect v-model="form.supply_status" placeholder="产品状态" :options="options.supply_status" multiple collapse-tags style="min-width: 130px" />
        <VCascader v-model="form.attribute_id" placeholder="产品分类" type="2" checkStrictly class="w-40" />
        <VSelect v-model="form.is_tc_complete" placeholder="是否发货完结" :options="options.is_tc_complete" select style="width: 130px" />
        <VSelect v-model="form.is_tc_order" placeholder="是否有头程备库单" :options="options.is_tc_order" style="width: 170px" />
        <VSelect v-model="form.is_many_purchase" placeholder="是否多PO" :options="options.is_tc_order" style="width: 130px" />
        <VSelect v-model="form.prepare_type" placeholder="备货方式" :options="options.prepare_type" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.has_combination" placeholder="组合sku" :options="options.is_tc_order" multiple collapse-tags style="min-width: 160px" />
        <el-input v-model="form.supplier_code" placeholder="供应商ID" class="w-40" />
        <VSelect v-model="form.platform" :options="options.platform" multiple collapse-tags style="min-width: 160px" placeholder="平台" />
        <VGroup>
          <el-select v-model="form.new.type" style="width: 130px">
            <el-option label="是否新品" value="is_new"></el-option>
            <el-option label="是否特采" value="is_special_purchase"></el-option>
          </el-select>
          <VSelect v-model="form.new.value" placeholder="请选择" :options="options.is_new" multiple collapse-tags style="min-width: 160px" />
        </VGroup>
        <VSelect v-model="form.is_dangerous" placeholder="是否危险品" :options="options.is_dangerous" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.sku_product_level" placeholder="产品等级" :options="options.sku_product_level" multiple collapse-tags style="min-width: 160px" />
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 130px">
            <el-option label="申请日期" value="create_time"></el-option>
            <el-option label="审核日期" value="audit_time"></el-option>
            <el-option label="需求日期" value="demand_time"></el-option>
            <el-option label="预计到货日期" value="expect_delivery_time"></el-option>
          </el-select>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
        <VSelect v-model="form.is_complete" :options="options.is_complete" multiple collapse-tags filterable clearable style="min-width: 140px" placeholder="是否完结" />
        <VSelect v-model="form.complete_type" :options="options.complete_type" multiple collapse-tags filterable clearable style="min-width: 140px" placeholder="完结类型" />
        <VSelect v-model="form.is_custom_product" :options="options.is_custom_product" multiple collapse-tags filterable clearable style="min-width: 140px" placeholder="是否定制化" /> 
      </template>
      <template #toolbar_btns>
        <VButton auth="/purchase/demand/sku/alter/generate_a_shipment_plan" type="primary" :loading="loadings.plan" @click="handleBatch('plan')">
          <svg-icon icon-class="sc" class="mr-1" style="font-size: 15px" />生成发货计划
        </VButton>
        <VButton type="primary" auth="/purchase/demand/sku/end" :loading="loadings.finish" @click="handleBatch('finish')">
           批量完结
        </VButton>
        <VButton type="primary" auth="/purchase/demand/sku/sale_change" :loading="loadings.sale_change" @click="handleBatch('sale_change')">
           批量修改
        </VButton>
        <VButton auth="/purchase/demand/sku/alter/cancel_an_order" type="primary" :loading="loadings.sale_change" @click="handleBatch('cancel')">
           批量取消
        </VButton>
        <VButton auth="/purchase/demand/sku/alter/change" type="primary" :loading="loadings.sale_change" @click="handleBatch('change')">
           批量变更
        </VButton>
        <!-- <VButton auth="/purchase/demand/sku/alter/generate_overseas_stock_orders" type="primary"
          @click="handleBatch('oversea')">
          <svg-icon icon-class="sc" class="mr-1" style="font-size: 15px" />生成海外仓备库订单
        </VButton> -->
        <VTotal :data="total" :options="[
          { title: '24小时未下单', key: 'one_day_nums' },
          { title: '48小时未下单', key: 'two_day_nums' },
          { title: '72小时未下单', key: 'three_day_nums' },
          { title: '超一月采购单未收货数量', key: 'one_month_nums' },
          { title: '超两月采购单未出库数量', key: 'two_month_nums' },
          { title: '超三月采购单未出库数量', key: 'three_month_nums' },
        ]" class="ml-auto" />
        <VAuth auth="/purchase/demand/sku/alter/derive" class="ml-auto">
          <el-dropdown trigger="click" @command="handleExport">
            <el-button>
              <i class="dk-iconfont icon-Upload" />
              导出<i class="dk-iconfont icon-ArrowDown" />
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="purchase_demand_sku">默认导出</el-dropdown-item>
                <el-dropdown-item command="purchase-demand-pr">PR单维度导出</el-dropdown-item>
                <el-dropdown-item command="purchase-demand-po">PO维度导出</el-dropdown-item>
                <el-dropdown-item command="purchase-demand-fh">发货计划维度导出</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <VExport class="absolute -right-full" ref="exportRef" mainKey="pds_id" :name="exportName" :tableRef="tableRef" task />
        </VAuth>
      </template>
    </VTable>
    <Add ref="addRef" :options="options" @success="query" />
    <VLog ref="logRef" />
    <Change ref="changeRef" :options="options" @success="query" />
    <Cancel ref="cancelRef" :options="options" @success="query" />
    <Ratio ref="ratioRef" :options="options" @success="query" />
    <AddPlan ref="addPlanRef" :options="options" @success="query" />
    <ChangeDialog ref="changeDialogRef" :options="options" @success="query" />
    <MoreRecords v-model="moreRecordsVisible" :id="moreRecordsId" :type="moreRecordsType" @close="moreRecordsId = null, moreRecordsType = null" />
    <AddPlanSingle ref="addPlanSingleRef" :options="options" @success="query"></AddPlanSingle>
    <SaleChange ref="saleChangeRef" :options="options.transport_type" @success="query"/>
  </VPage>
</template>

<script setup lang="jsx" name="Account">
import api from './api'
import Add from '@/views/demand/demand/components/Add'
import SimpleTable from '@/components/SimpleTable'
import { getOption } from '@/api/public'
import Change from '@/components/Change'
import VTotal from '@/components/VTotal'
import Ratio from './components/Ratio'
import AddPlan from './components/AddPlan'
import Cancel from './components/Cancel'
import ChangeDialog from './components/ChangeDialog'
import { ElMessage, ElMessageBox } from 'element-plus'
import MoreRecords from '@/components/MoreRecords/index'
import { resSkip, resMessage } from "@/utils/res"
import AddPlanSingle from './components/AddPlanSingle'
import SaleChange from './components/saleChange'
const baseName = 'purchase_demand'
const tableRef = ref()
const logRef = ref()
const loadings = reactive({})
const router = useRouter()
// 查询
const query = () => {
  tableRef?.value.query()
}

// 新增
const addRef = ref()

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: 'purchase_demand_change' }).then(res => res.data),
  getOption({ type: 'product' }).then(res => res.data),
  getOption({ type: 'purchase' }).then(res => res.data),
  getOption({ type: baseName }).then(res => res.data),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

// 导出
const exportName = ref('purchase_demand_sku')
const exportRef = ref()
const handleExport = (val) => {
  exportName.value = val
  nextTick(() => {
    exportRef?.value.open()
  })
}

// 批量操作
const addPlanRef = ref()
const saleChangeRef = ref()
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const pds_ids = selection.map(d => d.pds_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    plan: (is_skip = 1) => {
      const demand_type = selection[0].demand_type
      if (selection.some(d => d.demand_type !== demand_type)) {
        ElMessage.error('请选择相同需求类型的单据')
        return
      }
      if (demand_type === 1) {
        addPlanRef?.value.open(pds_ids)
        return
      }

      showLoading()
      api.plan({ pds_ids, is_skip }).then(res => {
        const { message, data } = res
        if (message) {
          if (data.is_skip !== 2) {
            ElMessage.error(message)
            return
          } else {
            resSkip({
              res,
              closeLoading,
              success: () => {
                query()
              },
              submit: () => {
                handle.plan(2)
              },
            })
          }
        } else {
          resMessage({
            res,
            success: () => {
              ElMessage.success('操作成功')
              close()
            }
          })
        }
      }).finally(closeLoading)
    },
    finish: () => {
      showLoading()
      api.batch_complete({ pds_ids }).then(res => {
          resMessage({
            res,
            success: () => {
              ElMessage.success('操作成功')
              close()
            }
          })
      }).finally(closeLoading)
    },
    sale_change: () => {
      saleChangeRef.value.open(pds_ids)
    },
    cancel: () => {
      cancelRef?.value.open(pds_ids)
    },
    change: () => {
      changeRef?.value.open({ pds_ids })
    },
    // oversea: () => {
    //   showLoading()
    //   api.getOversea({ pds_ids }).then(res => {
    //     const { destination_warehouse: send_warehouse_id, deliver_time: plan_shipment_time, transport_type: transport, detail } = res.data
    //     const commodity = detail.map(d => {
    //       const { sku, sale_id: sale_user_id, deliver_num: quantity, purchase_no: po_number, deliver_plan_no: pms_plan_no } = d
    //       return { sku, sale_user_id, quantity, po_number, pms_plan_no }
    //     })
    //     const query = {
    //       type: 'add',
    //       skuType: 'sku',
    //       send_warehouse_id,
    //       plan_shipment_time,
    //       transport,
    //       commodity: JSON.stringify(commodity)
    //     }
    //     to({ path: '/head_procedure/orderManagement/warehouseList/addFbaSea', query })
    //   }).finally(closeLoading)
    // },
    ratio: () => {
      ratioRef?.value.open({})
    },
  }
  handle[name]()
}

// 单行操作
const changeRef = ref()
const changeDialogRef = ref()
const ratioRef = ref()
const cancelRef = ref()
const addPlanSingleRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { pds_id, pd_id, demand_no, sku, sku_no,demand_type } = row
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    look: () => {
      addRef?.value.open(pd_id, true)
    },
    cancel: () => {
      cancelRef?.value.open([pds_id])
    },
    change: async () => {
      try {
        // showLoading()
        // await api.getChange({ pds_id })
        // closeLoading()
        // changeRef?.value.open({ demand_no, sku, sku_no })
        changeRef?.value.open({ pds_ids:[pds_id] })
      } catch (error) {
        closeLoading()
        console.error(error)
      }
    },
    adjust: () => {
      changeDialogRef?.value.open(row)
    },
    complete: () => {
      ElMessageBox.confirm('是否确认手动完结？', '取消', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.batch_complete({ pds_ids:[pds_id] }).then(res => {
            resMessage({
              res,
              success: () => {
                ElMessage.success('操作成功')
                close()
              }
           })
          }).finally(() => {
            closeLoading()
          })
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
    ratio: () => {
      ratioRef?.value.open(row)
    },
    toPath: () => {
      sessionStorage.setItem('_table_form', JSON.stringify({ tableForm: { input: { type: 'demand_no', value: row.demand_no } } }))
      router.push('/demand/change')
    },
    plan: () =>{
      addPlanSingleRef?.value.open(pds_id,demand_type)
    }
  }
  handle[name]()
}

// 列表配置
const tableOptions = reactive({
  size: 'small',
  rowConfig: { height: 206 },
  showHeaderOverflow: false,
  'show-overflow': false,
  formConfig: {
    data: {
      sku: { type: 'sku', value: '' },
      new: { type: 'is_new', value: '' }, // 组合
      input: { type: 'demand_no', value: '' },
      warehouse: { type: 'destination_warehouse', value: [] }, // 组合
      user: { type: 'purchase_user_id', value: [] },
      purchase_day: { start: null, end: null },
      num: { type: 'tc_leave_num', value: [], range: true },
      dateRange: { type: 'create_time', value: [], range: true },
    }
  },
  columns: [
    { type: 'checkbox', width: 40, fixed: 'left' },
    {
      title: '备库需求单号', minWidth: 240, slots: {
        default: ({ row }) => {
          return <div>
            <Copy copy={row.demand_no}><el-link type='primary' onClick={() => handleRow('look', row)}>{row.demand_no}</el-link></Copy>
            <VText title='需求类型' value={row.demand_type_name} />
            <VText title='需求部门' value={row.department_name} />
            <VText title='需求日期' value={row.demand_time} />
            <VText title='审核状态' value={row.demand_status_name} />
          </div>
        }
      }
    },
    {
      title: '申请人信息', minWidth: 230, slots: {
        default: ({ row }) => {
          return <div>
            <VText title='申请人' value={row.create_user} />
            <VText title='申请日期' value={row.create_time} />
          </div>
        }
      }
    },
    {
      minWidth: 120, slots: {
        header: () => <div>平台<br/>国家<br />目的仓</div>,
        default: ({ row }) => <div>
          <VText value={row.platform_name}></VText>
          <VText value={row.country_name}></VText>
          <VText value={row.destination_warehouse_name} line={2}></VText>
        </div>
      }
    },
    { field: 'transport_type_name', title: '预计运输方式', minWidth: 100 },
    {
      minWidth: 210, slots: {
        header: () => <div>sku信息</div>,
        default: ({ row }) => <div>
          <VText title="需求ID" value={row.sku_no} />
          <VText title='sku' value={row.sku} type='link'>
            <span class='whitespace-nowrap'>{row.sku}</span>
            {row.is_new === 2 ? <el-tag type="success" effect="dark" size='small' class='mx-1'>新</el-tag> : ''}
            {row.is_special_purchase === 2 ? <el-tag type="danger" size='small' effect="dark">特</el-tag> : ''}
            {row.is_dangerous === 2 ? <svg t="1731396340885" class="-mt-[1px]" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7755" width="24" height="24"><path d="M426.14784 160.23552l-368.27136 628.736a102.4 102.4 0 0 0 88.35072 154.17344h736.54272a102.4 102.4 0 0 0 88.35072-154.17344l-368.2304-628.736a102.4 102.4 0 0 0-176.7424 0z" fill="#FADE14" p-id="7756"></path><path d="M545.54624 158.96576a61.44 61.44 0 0 1 21.95456 21.99552l368.27136 628.736a61.44 61.44 0 0 1-53.00224 92.48768H146.2272a61.44 61.44 0 0 1-53.00224-92.48768l368.2304-628.736a61.44 61.44 0 0 1 84.09088-21.99552z m-63.73376 28.34432l-2.6624 3.97312-368.27136 628.736a40.96 40.96 0 0 0 30.55616 61.44l4.79232 0.24576h736.54272a40.96 40.96 0 0 0 37.51936-57.42592l-2.17088-4.25984-368.27136-628.736a40.96 40.96 0 0 0-68.03456-3.97312z" fill="#333333" p-id="7757"></path><path d="M450.1504 397.47584a385.26976 385.26976 0 0 1-123.2896 123.2896l19.6608 23.7568c12.288-8.6016 24.576-17.6128 36.864-27.4432v85.1968c-1.6384 67.1744-20.48 119.1936-56.5248 156.8768l23.7568 21.2992c39.3216-44.6464 60.2112-104.0384 62.2592-178.176v-66.7648h277.2992v-28.672h-121.6512c16.384-13.9264 33.1776-31.1296 49.9712-50.7904v-21.2992h-158.1056c6.9632-9.8304 13.5168-20.0704 20.0704-30.72l-30.3104-6.5536z m79.872 109.3632H395.6736c15.9744-14.336 31.1296-29.9008 45.4656-46.6944h138.8544c-16.384 17.6128-33.1776 33.1776-49.9712 46.6944z m73.728 101.5808v38.0928c0 13.1072-5.3248 19.6608-15.9744 19.6608-14.7456 0-31.1296-0.8192-49.152-2.4576l6.9632 27.8528c17.2032 0.8192 34.816 1.2288 52.8384 1.2288 23.3472-0.8192 35.2256-13.5168 35.2256-37.2736v-73.3184h-169.1648v153.6c0 24.576 13.1072 36.864 40.1408 36.864h129.4336c23.3472 0 39.3216-3.6864 47.5136-10.24 9.0112-8.192 15.1552-30.72 18.8416-66.7648l-28.2624-9.0112c-2.4576 23.7568-5.7344 39.7312-10.6496 47.9232-4.5056 6.9632-16.384 10.6496-35.2256 10.6496h-109.7728c-14.7456 0-22.1184-6.5536-22.1184-19.2512v-117.5552h109.3632z" fill="#333333" p-id="7758"></path></svg> : ''}
          </VText>
          {row.sku ? <div>
            <VText title='状态' value={row.sku_status_name} />
            <div class="grid grid-cols-2 gap-x-3">
              <VText title='周期' value={row.purchase_day} />
              <VText title='单箱' value={row.packing_qty} />
              <VText title='新品' value={row.is_new_name} />
              <VText title='特采' value={row.is_special_purchase_name} />
              <VText title='变更'>{row.is_change_name === '是' ? <el-link type='primary' onClick={() => handleRow('toPath', row)}>是</el-link> : '否'}</VText>
              <VText title='等级' value={row.sku_product_level_name} />
            </div>
            <VText title='是否退税' value={row.is_refund_tax_name} />
            <VText title='是否定制化' value={row.is_custom_product_name} />
          </div> : '-'}
        </div>
      }
    },
    {
      minWidth: 120, slots: {
        header: () => <div>辅助关系</div>,
        default: ({ row }) => <div>
          <VText value={row.main_sku} title="主"></VText>
          <VText value={row.ass_sku} title="辅">
            {row?.ass_sku?.map(item=>{
              return <div>{item.sku}*{item.quantity_auxiliary}</div>
            })}
          </VText>
        </div>
      }
    },
    { field: 'sku_cn_title', title: '产品名称', minWidth: 140, line: 4 },
    {
      field: 'is_combination_name', title: '是否组合sku', minWidth: 110, slots: {
        default: ({ row, rowIndex }) => {
          return <div>
            <VText value={row.is_combination_name} />
            {row.combination_data && row.combination_data.length ? <VText title="子sku信息" title-position="top" line="2">
              <VMore key={rowIndex}>
                {{
                  default: () => row.combination_data.map(d => <VText value={`${d.sku}*${d.sku_num}`} />)
                }}
              </VMore>
            </VText> : ''}
          </div>
        }
      }
    },
    {
      minWidth: 100, slots: {
        header: () => <div>ASIN<br />平台</div>,
        default: ({ row }) => <div>
          <VText value={row.asin}></VText>
          <VText value={row.platform_name}></VText>
        </div>
      }
    },
    {
      minWidth: 120, slots: {
        header: () => <div>品类</div>,
        default: ({ row }) => <VText value={row.attribute_name} line={3} />
      }
    },
    {
      minWidth: 160, slots: {
        header: () => <div>采购<br />开发</div>,
        default: ({ row }) => <div>
          <VText title='采购' value={row.purchase_user_name} />
          <VText title='开发' value={row.develop_user_name} />
        </div>
      }
    },
    {
      minWidth: 240, slots: {
        header: () => <div>供应商信息</div>,
        default: ({ row }) => <div>
          <VText title='供应商代码' value={row.supplier_code} />
          <VText title='供应商类型' value={row.purchase_type_name} />
          <VText title='结算方式' value={row.period_name} />
          <VText title='是否开票' value={row.is_invoice_name}></VText>
          <VText title='供应商负责人' value={row.director_user_name} />
        </div>
      }
    },
    {
      minWidth: 140, slots: {
        header: () => <div>库存信息</div>,
        default: ({ row }) => {
          return <div>
            <VText title='采购在途' value={row.inventory_data.purchase_transit} />
            <VText title='本地仓可用' value={row.inventory_data.local_num} />
            <VText title='本地仓待发' value={row.inventory_data.local_ready_shipment_num} />
            <VText title='海外仓可用' value={row.inventory_data.num} />
            <VText title='海外仓在途' value={row.inventory_data.transit_num} />
          </div>
        }
      }
    },
    {
      minWidth: 140, slots: {
        header: () => <div>销量信息</div>,
        default: ({ row }) => {
          return <div>
            <VText title='7天' value={row.sale.one_week_num} />
            <VText title='14天' value={row.sale.two_week_num} />
            <VText title='30天' value={row.sale.thirty_num} />
            <VText title='近四月'>&nbsp;</VText>
            {
              row.sale.detail.map(d => <VText title={d.month} value={d.num} />)
            }
          </div>
        }
      }
    },
    {
      minWidth: 150, slots: {
        header: () => <div>sku采销信息</div>,
        default: ({ row }) => {
          const sku_purchase_sale = row.sku_purchase_sale || {}
          return <div>
            <VText title='销售预估日销' value={sku_purchase_sale.estimate_day_sale_num} />
            <VText title='采购天数' value={sku_purchase_sale.purchase_day} />
            <VText title='可售天数' value={sku_purchase_sale.total_saleable_day} />
          </div>
        }
      }
    },
    {
      minWidth: 120, slots: {
        header: () => <div>需求数<br />价格<br />是否完结<br />完结类型</div>,
        default: ({ row }) => {
          return <div>
            <VText title='数量' value={row.demand_num} />
            <VText title='单价' value={row.purchase_price} />
            <VText title='总价' value={row.demand_num * row.purchase_price} />
            <VText title='完结' value={row.is_complete_name} />
            <VText title='完结类型' value={row.complete_type_name} />
          </div>
        }
      }
    },
    {
      minWidth: 900, slots: {
        header: () => {
          return <div>需求信息</div>
        },
        default: ({ row, rowIndex }) => {
          const itemRender = (item, field, idx, line) => {
            const value = item[field]
            if(Array.isArray(value)) {
              return <VMore key={idx} line={Math.max(2, line)}>
                {{
                  default: (line) => (value || []).map(d => <div class='w-full flex gap-2'>
                    <VText title='sku' value={d.sku} line={line} />
                    <VText title='数量' value={d.leave_num || d.inbound_num || 0} line={line} />
                  </div>)
                }}
              </VMore>
            } else {
              return <VText value={value} />
            }
          }
          return <SimpleTable key={rowIndex} columns={[
            { title: '销售', field: 'sale_name', span: 2 },
            { title: '数量', field: 'demand_num' },
            { title: '部门', field: 'department_name', span: 3 },
            { title: '待下单数量', field: 'wait_order_num', span: 4 },
            { title: '剩余发货数', field: 'tc_leave_num', span: 2 },
            { title: '已入库数量', field: 'inbound_num', span: 4 },
            { title: '已建单数量', field: 'plan_num', span: 2 },
            ]} data={row.demand_info} line={2} itemRender={itemRender} dialogWidth={1000} />
        }
      }
    },
    {
      minWidth: 100, slots: {
        header: () => <div>待下单数量<br />剩余发货数<br />已入库数量<br />已建单数量</div>,
        default: ({ row }) => {
          const {leave_data = [], inbound_data = []} = row
          return <div>
            {!leave_data.length ? '0' : leave_data.length === 1 ? leave_data[0].leave_num : <VMore value={() => leave_data.map(d => <div>{d.sku}: {d.leave_num}</div>)}></VMore>}
            <VText value={row.tc_leave_num} />
            {!inbound_data.length ? '0' : inbound_data.length === 1 ? inbound_data[0].inbound_num : <VMore value={() => inbound_data.map(d => <div>{d.sku}: {d.inbound_num}</div>)}></VMore>}
            <VText value={row.plan_order_num} />
          </div>
        }
      }
    },
    {
      minWidth: 220, slots: {
        header: () => <div>采购信息</div>,
        default: ({ row, rowIndex }) => {
          const purchase = row.purchase || []
          const abnormal_data = row.abnormal_data || []
          const content = () => purchase.map((d, i) => <div class='w-full'>
            <VText title='采购单' value={d.purchase_no} type='link' />
            <VText title='备货方式' value={d.prepare_type_name} />
            <VText title='发货仓' value={d.destination_warehouse_name} />
            <div class="grid grid-cols-2 gap-x-3">
              <VText title='下单数' value={d.purchase_num}></VText>
              <VText title='收货数' value={d.deliver_num}></VText>
            </div>
            <div class="grid grid-cols-2 gap-x-3">
              <VText title='待质检数' value={d.wait_qa_num}></VText>
              <VText title='入库数' value={d.inbound_num}></VText>
            </div>
            <VText title='预计到货时间' value={d.expect_delivery_time}></VText>
            <VText title='采购单状态' value={d.audit_status_name}></VText>
          </div>)
          const view = () => {
            if (row.abnormal_flag !== '是') return
            ElMessageBox({
              title: '查看异常详情',
              showCancelButton: true,
              showConfirmButton: false,
              cancelButtonText: '关闭',
              message: () => <div class='flex flex-col gap-2'>
                {
                  abnormal_data.map((d, i) => <div>
                    <VText title='异常单' value={d.abnormal_no}></VText>
                    <VText title='异常单状态' value={d.abnormal_status_name}></VText>
                  </div>)
                }
              </div>
            })
          }
          return purchase.length ? <div>
            <VMore key={'1' + rowIndex} value={content} />
            <VText title='是否到货异常' value={row.abnormal_flag} type={row.abnormal_flag === '是' ? 'button' : ''} onClick={view} />
          </div> : <strong>{row.sku_purchase_status_name || 'sku_purchase_status_name 数据不存在'}</strong>
        }
      }
    },
    {
      minWidth: 160, slots: {
        header: () => '备料单信息',
        default: ({ row, rowIndex }) => <VMore key={rowIndex}>
          {{
            default: (line) => (row.plan || []).map(d => <div class='w-full'>
              <VText title='备料单号' value={d.plan_no} line={line} title-position='top' />
              <VText title='备料数量' value={d.demand_num} line={line} />
              <VText title='备料余料' value={d.leave_num} line={line} />
            </div>)
          }}
        </VMore>
      }
    },
    {
      minWidth: 170, slots: {
        header: () => '采购暂停信息',
        default: ({ row, rowIndex }) => {
          const { pause_data } = row
          if (!pause_data?.length) return '-'
          const content = () => pause_data.map(d => {
            return <div>
              <VText title='人员' value={d.pause_user}></VText>
              <VText title='时间' value={d.pause_time}></VText>
              <VText title='原因' value={d.pause_reason} line={2} />
              <el-button link type="primary" onClick={() => handleMoreRecords(row, 1)}>更多记录</el-button>
            </div>
          })
          return <VMore value={content} key={rowIndex} />
        }
      }
    },
    {
      minWidth: 160, slots: {
        header: () => '采购驳回信息',
        default: ({ row, rowIndex }) => {
          const { reject_data } = row
          if (!reject_data?.length) return '-'
          const content = () => reject_data.map(d => <div>
            <VText title='人员' value={d.reject_user}></VText>
            <VText title='数量' value={d.reject_num}></VText>
            <VText title='原因' value={d.reject_type_name} line={2} />
            <VText title='备注' value={d.reject_reason} line={2} />
            <el-button link type="primary" onClick={() => handleMoreRecords(row, 2)}>更多记录</el-button>
          </div>
          )
          return <VMore value={content} key={rowIndex} />
        }
      }
    },
    {
      minWidth: 240, slots: {
        header: () => <div>发货计划信息</div>,
        default: ({ row, rowIndex }) => {
          const { deliver_plan } = row
          if (!deliver_plan?.length) return '-'
          const content = () => deliver_plan.map(d => <div>
            <VText title='发货计划编号' value={d.plan_no}></VText>
            <VText title='预计发货时间' value={d.deliver_time}></VText>
            <VText title='预计发货数量' value={d.deliver_num}></VText>
          </div>)
          return <VMore value={content} key={rowIndex} />
        }
      }
    },
    {
      minWidth: 260, slots: {
        header: () => <div>头程发货信息</div>,
        default: ({ row, rowIndex }) => {
          const { deliver_data } = row
          if (!deliver_data?.length) return '-'
          const content = () => deliver_data.map(d => <div>
            <VText title='下单时间' value={d.order_time}></VText>
            <VText title='FBAcode' value={d.fba_code}></VText>
            <VText title='出库单号' value={d.deliver_no}></VText>
            <VText title='目的仓' value={d.warehouse_name}></VText>
            <VText title='物流渠道' value={d.channel_name}></VText>
            <VText title='出库数量' value={d.deliver_num}></VText>
            <VText title='发货时间' value={d.shipment_time}></VText>
          </div>)
          return <VMore value={content} key={rowIndex} />
        }
      }
    },
    {
      field: 'detail_remark', title: '计划备注', minWidth: 150, line: 4
    },
    {
      title: '操作', width: 110, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          const { sku_purchase_status,plan_order_status } = row
          // 采购状态 1等待审核完成 2待供应商负责人确认 3需求驳回 4采购暂停 5待下单 6部分下单 7已全部下单 8取消采购
          return [<div class='nm flex gap-1 flex-wrap'>
            {[1,2].includes(plan_order_status) ? <VButton auth="/purchase/demand/sku/alter/generate_a_shipment_plan" type="primary" link onClick={() => handleRow('plan', row)}>生成发货计划</VButton>: ''}
            {[2, 3, 4, 5, 6, 7].includes(sku_purchase_status) && row.is_cancel === 1 ? <VButton auth="/purchase/demand/sku/alter/cancel_an_order" link type="primary" onClick={() => handleRow('cancel', row)}>取消订单</VButton> : ''}
            {[2, 3, 4, 5, 6, 7].includes(sku_purchase_status) ? <VButton auth="/purchase/demand/sku/alter/change" link type="primary" loading={loadings['change' + rowIndex]} onClick={() => handleRow('change', row, rowIndex)}>变更</VButton> : ''}
            {[3, 4, 5, 6, 7].includes(sku_purchase_status) ? <VButton auth="/purchase/demand/sku/end" link type="primary" onClick={() => handleRow('complete', row)}>手动完结</VButton> : ''}
            {[1, 2, 3, 4].includes(sku_purchase_status) ? <VButton auth="/purchase/demand/sku/alter/set_the_proportion_of_cargo_owners" link type="primary" onClick={() => handleRow('ratio', row)}>设置货主比例</VButton> : ''}
            {[6, 7].includes(sku_purchase_status) ? <VButton auth="/purchase/demand/sku/alter/adjust_the_purchasing_body" link type="primary" onClick={() => handleRow('adjust', row)}>调整采购主体</VButton> : ''}
          </div>]
        }
      }
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => {
        api.total({ ...form, ...page }).then(res => {
          total.value = res.data[0]
        })
        return api.query({ ...form, ...page })
      } 
    }
  }
})


// 统计数据
const total = ref({})

const moreRecordsVisible = ref(false)
const moreRecordsId = ref(null)
const moreRecordsType = ref(null)
const handleMoreRecords = (row, type) => {
  moreRecordsVisible.value = true
  moreRecordsId.value = row.pds_id
  moreRecordsType.value = type
}

// 打开页面或重新激活页面后主动调用方法
// sessionStorage.setItem('PURCHASE_HANDLE', JSON.stringify({pds_id: '1871', demand_no: 'PR202406030018', sku: '3611905', sku_no: '240603000005'}))
const handleChange = () => {
  const params = JSON.parse(sessionStorage.getItem('PURCHASE_HANDLE') || '{}')
  if(params?.demand_no) {
    tableRef?.value?.setForm({input: { type: 'demand_no', value: params.demand_no }, sku: { type: 'sku', value: params.sku }})
    query()
    handleRow('change', params)
    sessionStorage.removeItem('PURCHASE_HANDLE')
  }
}
nextTick(() => {
  handleChange()
})
onActivated(() => {
  handleChange()
})
</script>